testStopSzenarioATR <- function(groupcode, pattern, direction="long", duration=5, entry="c0",
                                Pversion=0, verbose=TRUE, table="orderLogicTest") {
  if('package:PerformanceAnalytics' %in% search() || require('PerformanceAnalytics',quietly=TRUE)) {}
  
  insertSqlString <- function() {
    sql <- sprintf("INSERT INTO `va_stratlab`.`%s` 
      (`id`, `group`, `pattern`, `symbol`, `Pversion`, `method`, `entry`,
      `stoplosslimit`, `stopwinlimit`, `direction`, `duration`, 
      `numberoftrades`, `pctstopped`, `stoplosspct`, `stopwinpct`, 
      `returnmean`, `returnsd`, `returnddev`, `pctwin`)", table)
    values <- sprintf("VALUES
      (NULL, '%s', '%s', '%s', '%d', '%s', '%s',
      '%f', '%f', '%s', '%d',
      '%d', '%f', '%f', '%f', 
      '%f', '%f', '%f', '%f')",
      groupcode, pattern, "", Pversion, "ATRPct", entry,
      round(LL, 2), round(WL, 2), direction, duration,
      ex["numberOfTrades",], ex["stopPct",], ex["stoplossPct",], 
      ex["stopwinPct",], ex["returnMean",], ex["returnSd",], 
      ex["returnDDev",], ex["pctWin",])
    return (paste(sql, values))
  }
  con <- connectToVadb()
  groupinfo <- getDBGroup(groupcode)  # retrieve table with stock_id, code, from, to
  patternlist <- getCSPGroupPattern(groupcode, Pversion=Pversion, daysbefore=300, daysafter=20)  # contains all members of a group
  patternlistnames <- names(patternlist)

  ATRvec <- 0:9
  ATRLL <- exp(ATRvec/5)-1
  # > ATRLL
  # [1] 0.00 0.22 0.49 0.82 1.23 1.72 2.32 3.06 3.95 5.05
  ATRWL <- ATRLL
  for (LL in ATRLL) {
    for (WL in ATRWL) {
      returnsdf <- data.frame()
      if (verbose==TRUE) {
        cat ("ATRLL: ", round(LL, 2), "ATRWL: ", round(WL, 2), "\n")
      }
      for (i in 1:length(patternlist)) {  # loop throught all group members
        myOrderXTS <- patternlist[[i]][,pattern]                # i.e. Hammer of DJ
        symname <- paste(patternlistnames[i], ".vadb", sep="")  # i.e. DJ.vadb
        fromtodates <- getGroupMember(groupinfo, patternlistnames[i])
        subsetstring <- paste(fromtodates[1], "/", sep="")       # ensure that TS and myOrderXTS have same indexes
        XATR <- ATR(cbind(Hi(get(symname)), Lo(get(symname)), Cl(get(symname))))[subsetstring]
        OHLC <- get(symname)[subsetstring]
        
        if (entry=="c0") {
          EntryPrice <- Cl(OHLC)
        } else if (entry=="o1") {
          EntryPrice <- as.xts(Next(Op(OHLC)))
        } else if (entry=="c1") {
          EntryPrice <- as.xts(Next(Cl(OHLC)))
        }
        
        if (direction=="long") {
          OrderTS <- merge(myOrderXTS, 0, 
                           (LL>0) * EntryPrice-LL*XATR[,'atr'], 
                           (WL>0) * EntryPrice+WL*XATR[,'atr'])
          colnames(OrderTS) <- c("long", "short", "stoploss", "stopwin")
        } else if (direction=="short") {
          OrderTS <- merge(myOrderXTS, 0,
                           (LL>0) * EntryPrice+LL*XATR[,'atr'], 
                           (WL>0) * EntryPrice-WL*XATR[,'atr'])
          colnames(OrderTS) <- c("short", "long", "stoploss", "stopwin")
        }
        
        if (verbose==TRUE) {
          cat ("calculate", patternlistnames[i], "\n")
        }
        #if (WL>0 & LL>0) return(cbind(OHLC, XATR, OrderTS))
        
        OL <- orderLogic(OHLC, OrderTS, n=duration, entry=entry)
        OLDF <- as.data.frame(OL)
        # debug line- to remove!
        # if (WL>1 & LL>1) return(OLDF)
      
        if (dim(returnsdf)[1] == 0) {
          if (dim(OLDF)[1] >= 1) {  # rbind only if pattern have been found
            OLDF$symbol <- patternlistnames[i]
            returnsdf <- OLDF
          }      
        } else {
          if (dim(OLDF)[1] >= 1) {  # rbind only if pattern have been found
            OLDF$symbol <- patternlistnames[i]
            returnsdf <- rbind(returnsdf, OLDF)
          }      
        }
      }
      # now the returns can be examined
      ex<- examineOrderTSDF(returnsdf)
      # write observations to db
      dbSendQuery(con, insertSqlString())
    }
  }
  # disconnect from vadb
  disconnectFromVadb(con)
  return(returnsdf)
}